package com.zd.kids.ui.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.Utils;
import com.google.gson.Gson;
import com.hyy.libray.common.BaseUtils;
import com.hyy.libray.common.Constant;
import com.hyy.libray.presenter.IBasePresenter;
import com.hyy.libray.ui.activity.BaseActivity;
import com.zaaach.citypicker.util.ScreenUtil;
import com.zd.kids.DataBean.BaseDataBean;
import com.zd.kids.DataBean.CommonStatusDataBean;
import com.zd.kids.R;
import com.zd.kids.common.ToastUtils;
import com.zd.kids.net.CustomApi;
import com.zd.kids.net.CustomObserver;
import com.zd.kids.net.HttpMethod;
import com.zd.kids.ui.view.VerificationCodeInput;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class InputCodeActivity extends BaseActivity {

    @BindView(R.id.tv_tips)
    TextView tvTips;
    @BindView(R.id.view_code_input)
    VerificationCodeInput viewCodeInput;
    @BindView(R.id.tv_countdown)
    TextView tvCountdown;
    @BindView(R.id.tv_confirm)
    TextView tvConfirm;
    @BindView(R.id.tv_resend)
    TextView tvReSend;
    @BindView(R.id.tv_resend_tips)
    TextView tvResendTips;

    /**
     * 获取布局文件地址
     */
    @Override
    public int getLayoutResId() {
        return R.layout.activity_input_code;
    }


    public static final String MOBILE_KEY = "MOBILE_KEY";

    public static final String MOBILE_COUNTRY_KEY = "MOBILE_COUNTRY_KEY";

    public static final String PERSON_INFO_KEY = "PERSON_INFO_KEY";


    private String mMobile;

    private String mMobileCountryId;

    private HashMap<String, String> personInfo;

    private String testCode = "";

    private String headPhotoPath = "";

    private boolean isLogin;

    /**
     * 初始化布局
     */
    @Override
    public void initView() {
        initTitle(getString(R.string.login_qm));

        tvTips.setText("");

        mMobile = getIntent().getStringExtra(MOBILE_KEY);

        isLogin = getIntent().getBooleanExtra("Login", false);

        mMobileCountryId = getIntent().getStringExtra(MOBILE_COUNTRY_KEY);

        testCode = getIntent().getStringExtra("code");

        String per = getIntent().getStringExtra(PERSON_INFO_KEY);

        Gson gson = new Gson();

        personInfo = new HashMap();

        personInfo = gson.fromJson(per, HashMap.class);

        viewCodeInput.setOnCompleteListener(new VerificationCodeInput.Listener() {
            @Override
            public void onComplete(String content, boolean isComplete) {
                if (isComplete) {
                    tvConfirm.setBackgroundResource(R.drawable.shape_bt_bg);
                } else {
                    tvConfirm.setBackgroundResource(R.drawable.shape_btgray_bg);
                }
            }

        });

    }

    @Override
    public void initData() {
        super.initData();
        if (personInfo != null) {
            mMobile = personInfo.get("mobile");
            mMobileCountryId = personInfo.get("countryid");
            headPhotoPath = personInfo.get("photo");
        }

        tvTips.setText(getString(R.string.we_inputed)+"\n****" + getPrivateMobile(mMobile));

        startCountDown();

        viewCodeInput.setContent(testCode);
    }


    private String getPrivateMobile(String mMobile) {
        if (!TextUtils.isEmpty(mMobile)) {
            if (mMobile.length() > 4) {
                return "****" + mMobile.substring(mMobile.length() - 4);
            } else {
                return "****" + mMobile;
            }
        }
        return "";
    }

    /**
     * 获取Presenter，不用MVP，可以为空
     *
     * @return
     */
    @Override
    protected IBasePresenter onBasePresenter() {
        return null;
    }


    @OnClick({R.id.tv_confirm, R.id.tv_resend})
    public void onViewClicked(View view) {
        if (BaseUtils.isFastClick()) {
            return;
        }
        KeyboardUtils.hideSoftInput(this);
        Intent intent;
        switch (view.getId()) {
            case R.id.tv_confirm:
                KeyboardUtils.hideSoftInput(this);
                String code = viewCodeInput.getContent();
                if (!TextUtils.isEmpty(code) && code.length() == 6) {

                    if (!isLogin) {

                        register(code);
                    } else {
                        userLogin(code);
                    }

                } else {
                    ToastUtils.getIntence().makeTextShow(getString(R.string.code_error));
                }


                break;
            case R.id.tv_resend:
                KeyboardUtils.hideSoftInput(this);
                if (!isLogin) {
                    sendRegistSms(mMobile, mMobileCountryId);
                } else {
                    getLoginCode(mMobile, mMobileCountryId);
                }
                break;
        }
    }


    private void userLogin(String code) {
        showLoading();
        HttpMethod.getIntence().userLogin(mMobile, mMobileCountryId, code, new CustomObserver<CommonStatusDataBean>() {
            @Override
            public void onSuccess(CommonStatusDataBean commonStatusDataBean) {
                SPUtils.getInstance(Constant.GAPSK_AI_QM).put("jwt", commonStatusDataBean.getJwt());
                Intent intent = new Intent(InputCodeActivity.this, MainTypeActivity.class);
                startActivity(intent);
                finish();
            }

            @Override
            public void onError(String errorCode) {
                disLoading();
            }
        });
    }


    private void register(String code) {
        showLoading();
        personInfo.put("code", code);
        Observable<BaseDataBean<CommonStatusDataBean>> observable = Observable.just(personInfo)
                .flatMap((Function<Map<String, String>, ObservableSource<Map<String, String>>>) params -> {

                    if (!TextUtils.isEmpty(headPhotoPath)) {
                        String head64 = BaseUtils.fileToBase64(new File(headPhotoPath));

                        if (!TextUtils.isEmpty(head64)) {
                            params.put("photo", head64);
                        } else {
                            params.put("photo", "");
                        }
                    } else {
                        params.put("photo", "");
                    }


                    return Observable.just(params);
                })
                .flatMap(new Function<Map<String, String>, ObservableSource<BaseDataBean<CommonStatusDataBean>>>() {
                    @Override
                    public ObservableSource<BaseDataBean<CommonStatusDataBean>> apply(Map<String, String> stringStringMap) throws Exception {

                        return CustomApi.getIntence().getApi().register(stringStringMap);
                    }
                });

        observable
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Observer<BaseDataBean<CommonStatusDataBean>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(BaseDataBean<CommonStatusDataBean> commonStatusDataBeanBaseDataBean) {
                        disLoading();

                        if (commonStatusDataBeanBaseDataBean.getCode() == 200) {
                            CommonStatusDataBean commonStatusDataBean = commonStatusDataBeanBaseDataBean.getData();
                            SPUtils.getInstance(Constant.GAPSK_AI_QM).put("jwt", commonStatusDataBean.getJwt());
                            Intent intent = new Intent(InputCodeActivity.this, RegistSuccActivity.class);
                            startActivity(intent);
                            finish();
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        disLoading();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    private void sendRegistSms(String mobile, String mMobileCountryId) {
        HttpMethod.getIntence().registSendSms(mobile, mMobileCountryId, new CustomObserver<String>(this) {
            @Override
            public void onSuccess(String baseDataBean) {

                tvTips.setText(getString(R.string.we_inputed)+"\n****" + getPrivateMobile(mMobile));
                tvResendTips.setVisibility(View.VISIBLE);
                viewCodeInput.setContent(baseDataBean);
                startCountDown();
            }

            @Override
            public void onError(String errorCode) {

            }
        });
    }


    int mCountDownTime = 60;

    private void startCountDown() {
        Observable.interval(1, TimeUnit.SECONDS)
                .take(mCountDownTime)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        tvReSend.setTextColor(0xFF595959);
                        tvReSend.setEnabled(false);
                    }

                    @Override
                    public void onNext(Long aLong) {
                        tvCountdown.setText(getString(R.string.haishen) + (mCountDownTime - aLong - 1) + "秒");
                        LogUtils.i("startCountDown:" + aLong);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        tvReSend.setTextColor(getResources().getColor(R.color.title_top_color));
                        tvReSend.setEnabled(true);
                        LogUtils.i("onComplete:");
                    }
                });
    }


    private void getLoginCode(String mobile, String mMobileCountryId) {
        showLoading();
        HttpMethod.getIntence().getloginMobileSms(mobile, mMobileCountryId, new CustomObserver<String>() {
            @Override
            public void onSuccess(String code) {
                tvResendTips.setVisibility(View.VISIBLE);
                disLoading();

                tvTips.setText(getString(R.string.we_inputed)+"\n****" + getPrivateMobile(mMobile) + "(" + code + ")");


                startCountDown();
            }

            @Override
            public void onError(String errorCode) {
                disLoading();
            }
        });
    }
}
